import React, { FC, useEffect, useState } from 'react'
import { getUserSelectList, getConfirmUpdatePrice } from '@/api/prepaidCard'
import { Popup } from 'antd-mobile'
import { PrepaidCardInfo, ResPrepaidCard, SelectCardUpdatePriceResponse } from '@/types/prepaidCard'
import { useAsyncEffect } from 'ahooks'
import { CourseId } from '@/types'
import { XBusinesslineId } from '@/constants'
import { Product } from '@/types/product'
import { decode, encode } from 'js-base64'
import { useAppSelector, useAppDispatch } from '@/store'
import {
  changePriceParam,
  confirmUpdatePrice,
  selectCardUpdatePriceInfo,
  selectConfirmUpdatePriceParam,
} from '@/store/confirmPay'
//changePriceParam
interface PrepaidCardProps {
  productInfo: Product[]
  course_id: CourseId
  balance: string | number
  setVisible: (status: boolean) => void
}
const prepaidCard: FC<PrepaidCardProps> = (props) => {
  const dispatch = useAppDispatch() //
  // 注：若商品申请退费时讲义已签收，需根据签收的讲义按分类扣除费用。
  const [select, setSelect] = useState<string>('')
  const agreestyleStr = 'text-red-E02727 icon-icon_selected'
  const [prepaidCardData, setPrepaidCardData] = useState<ResPrepaidCard>()
  useAsyncEffect(async () => {
    const res = await getUserSelectList({
      course_id: props.course_id,
      'X-Businessline-Id': XBusinesslineId,
    })
    setPrepaidCardData(res.data)
  }, [])

  const [selectCard, setSelectCard] = useState<PrepaidCardInfo>()
  const updatePrise = useAppSelector(selectCardUpdatePriceInfo)
  const paramTmp = useAppSelector(selectConfirmUpdatePriceParam)

  useAsyncEffect(async () => {
    const product_info = props.productInfo.map((val) => {
      return {
        product_id: val.productId,
        price: val.price,
        product_num: 1,
        brand: val.product_type,
      }
    })
    if (selectCard) {
      const param = {
        ...paramTmp,
        product_info: decode(JSON.stringify(product_info)),
        use_gold: '1',
        balance: props.balance.toString(),
        choose_prepaid_cards: [
          {
            card_number: selectCard.card_number,
            card_balance_amount: selectCard.card_balance_amount.toString(),
          },
        ],
        'X-Businessline-Id': XBusinesslineId,
      }

      const res = await getConfirmUpdatePrice(param)

      dispatch(confirmUpdatePrice(res.result.data))
      dispatch(changePriceParam(param))
    }
  }, [selectCard])
  // const updatePriseFn = async () => {}
  return (
    <Popup
      visible={true}
      onMaskClick={() => {
        props.setVisible(false)
      }}
      bodyStyle={{ height: '50rem' }}
    >
      <div className=" pl-r1.6 pr-r1.6 ">
        <div className=" text-center text-gray-333333 text-r1.6 leading-r1.6 font-medium font-medium-family relative pl-r1.0 pr-r1.0 pt-r1.6 pb-r2.0">
          <span>礼品卡</span>
          <span
            className=" absolute right-0 w-r2.0 h-r2.0 text-r1.6"
            onClick={() => {
              props.setVisible(false)
            }}
          >
            <i className="iconfont icon-icon_colse"></i>
          </span>
        </div>
        <div className=" ">
          {updatePrise ? (
            <span>选中1张礼品卡,共抵扣￥{updatePrise.prepaidReduced}</span>
          ) : (
            <span>选中0张礼品卡,共抵扣￥{0}</span>
          )}
        </div>
        <div>
          {prepaidCardData?.list.map((val, key) => {
            return (
              <div
                key={key}
                onClick={() => {
                  if (val.card_number === select) {
                    setSelect('')
                    setSelectCard(undefined)
                  } else {
                    setSelect(val.card_number)
                    setSelectCard(val)
                  }
                }}
              >
                <div>面值v{val.card_denomination}</div>
                <div>
                  {' '}
                  <span>卡内余额</span>
                  <span>¥ {val.card_balance}</span>
                  <span>
                    <i
                      className={
                        'inline-block iconfont text-r1.2 ' +
                        (select === val.card_number
                          ? agreestyleStr
                          : ' icon-icon_unselected  text-gray-878E9A ')
                      }
                    ></i>
                  </span>
                </div>
                <div>
                  <span>有效期：{val.expiration_date_desc}</span>
                </div>
              </div>
            )
          })}
        </div>
      </div>
      <div className="w-full fixed bottom-0  h-r8.6  bg-white">
        <div className=" h-r6.0 pl-r1.6 pr-r1.6 pt-r0.9 pb-r1.0 leading-r6.0 overflow-hidden text-center ">
          <span
            className="  text-r1.4 h-r4.0 w-r17.0  text-white leading-r4.0 rounded-r2.0  bg-gradient-to-r from-orange-FF664F to-orange-FF3627  inline-block "
            onClick={() => {
              props.setVisible(false)
            }}
          >
            确定
          </span>
        </div>
      </div>
    </Popup>
  )
}

export default prepaidCard
